package com.first.nell.home

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.first.nell.ProjectApplication
import com.first.nell.base.BaseFragment
import com.first.nell.components.dialog.CustomerServiceDialog
import com.first.nell.components.dialog.PermissionsHomeDialog
import com.first.nell.components.dialog.UsageStatsPermissionGuaidDialog
import com.first.nell.data.ReqBase
import com.first.nell.databinding.FragmentFirstNellHomeBinding
import com.first.nell.enums.PageTagEnum
import com.first.nell.extend.*
import com.first.nell.launch.UserStateViewModel
import com.first.nell.utils.AppConfigUtil
import com.first.nell.utils.UserStateUtil
import com.first.nell.utils.analytics.util.AnalyticsUtil
import com.zhi.syc.data.ASSycManager
import java.lang.ref.WeakReference

/** 首页 */
class HomeFragment : BaseFragment() {

    //布局binding
    private lateinit var mFirstNellFragmentFirstNellBinding: FragmentFirstNellHomeBinding

    //权限弹框
    private val mPermissionsHomeDialog = PermissionsHomeDialog()

    //首页viewModel
    private val mHomeViewModel by lazy {
        ViewModelProvider(this)[HomeViewModel::class.java]
    }

    //用户流程viewModel
    private val mUserStateViewModel by lazy {
        ViewModelProvider(this)[UserStateViewModel::class.java]
    }

    override fun onFirstNellBindingFirstNellViewFirstNellModel(): List<ViewModel> {
        val list = mutableListOf<ViewModel>()
        list.add(mHomeViewModel)
        list.add(mUserStateViewModel)
        return list
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?,
    ): View {
        mFirstNellFragmentFirstNellBinding =
            FragmentFirstNellHomeBinding.inflate(inflater, container, false)
        return mFirstNellFragmentFirstNellBinding.root
    }

    @SuppressLint("SetTextI18n")
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        try {
            //增加弱牵引
            (requireActivity() as HomeActivity).weakFirstNellHomeFirstNellFragment =
                WeakReference(this)

            //获取用户状态回调
            mUserStateViewModel.onFirstNellFetchFirstNellUserFirstNellStateFirstNellLiveData.observe(
                viewLifecycleOwner
            ) {
                if (it.isSuccess) {
                    startFirstNellToFirstNellNextFirstNellFromFirstNellPage(
                        PageTagEnum.home
                    )
                }
            }

            //获取待授权的权限列表
            mHomeViewModel.onFirstNellIsFirstNellNeedFirstNellToFirstNellRequireFirstNellPermissionsFirstNellLiveData.observe(
                viewLifecycleOwner
            ) {
                if (it.isNullOrEmpty()) {
                    //权限授权处理完成
                    onFirstNellPermissionsFirstNellRequestFirstNellAllFirstNellPass()
                } else {
                    //请求权限
                    requestFirstNellSpecFirstNellPermissions(it)
                }
            }

            //获取首页额度回调
            mHomeViewModel.onFirstNellFetchFirstNellHomeFirstNellCreditFirstNellLiveData.observe(
                viewLifecycleOwner
            ) {
                if (it.isSuccess) {
                    it.getOrNull()?.let { result ->
                        result.fetchLastCredit()?.let { item ->
                            mFirstNellFragmentFirstNellBinding.textHomeLoanLimitUnit.text =
                                item.currency
                            mFirstNellFragmentFirstNellBinding.textHomeLoanLimit.text =
                                item.amount.toFirstNellFinanceFirstNellString()

                            mFirstNellFragmentFirstNellBinding.textHomeGoodRecordMaxAmount1.text =
                                item.currency +" " + (item.increasedAmount1?.toFirstNellFinanceFirstNellString())
                            mFirstNellFragmentFirstNellBinding.textHomeGoodRecordMaxAmount2.text =
                                item.currency +" " + (item.increasedAmount2?.toFirstNellFinanceFirstNellString())

                            mFirstNellFragmentFirstNellBinding.textHomeGoodRecordMinAmount1.text =
                                item.currency +" " + (item.amount.toFirstNellFinanceFirstNellString())
                            mFirstNellFragmentFirstNellBinding.textHomeGoodRecordMinAmount2.text =
                                item.currency +" " + (item.amount.toFirstNellFinanceFirstNellString())
                        }
                    }
                }
            }

            //点击开始申请
            mFirstNellFragmentFirstNellBinding.submitHome.setOnClickListener {
                mFirstNellFragmentFirstNellBinding.submitHome.recordFirstNellClickFirstNellEvent()
                //mHomeViewModel.isFirstNellNeedFirstNellToFirstNellRequireFirstNellPermissoins()

                //判断下权限页权限
                val permissionList =
                    AppConfigUtil.getFirstNellPermissionsFirstNellOfFirstNellHomeFirstNellPage()
                println("========= permissionList")
                println(permissionList)
                val isAgreePermissions =
                    ProjectApplication.context.isFirstNellAgreeFirstNellSpecFirstNellPermissions(
                        permissionList
                    )
                println("============ ${isAgreePermissions}")
                if (isAgreePermissions) {
                    //权限授权处理完成
                    onFirstNellPermissionsFirstNellRequestFirstNellAllFirstNellPass()
                } else {
                    //查询权限
                    val curPermissionList =
                        PermissionsHomeDialog.getPermissionList(requireActivity())

                    //展示
                    if (curPermissionList.isNotEmpty()) {
                        //设置权限数据
                        mPermissionsHomeDialog.setPermissionList(curPermissionList)

                        //展示
                        mPermissionsHomeDialog.setShowDiaog(requireActivity().supportFragmentManager)
                    }
                }
            }

            //初始化权限弹框
            //设置拒绝设备权限回调
            mPermissionsHomeDialog.setPhoneSateDenyClickListener {
                mPermissionsHomeDialog.dismiss()
            }

            //设置请求权限回调
            mPermissionsHomeDialog.setStartRequestPermissionClickListener { permission ->
                //请求权限
                requestFirstNellSpecFirstNellPermissions(
                    arrayOf(
                        android.Manifest.permission.READ_SMS,
                        android.Manifest.permission.READ_PHONE_STATE
                    )
                )
            }

            //设置同意所有权限回调
            mPermissionsHomeDialog.setAllRequestPermissionAgreeListener {
                //权限授权处理完成
                onFirstNellPermissionsFirstNellRequestFirstNellAllFirstNellPass()
            }

            //点击客服
            mFirstNellFragmentFirstNellBinding.imageHomeCustomerService.setOnClickListener {
                CustomerServiceDialog.showFirstNellDialog(requireActivity().supportFragmentManager)
            }

            //获取首页额度
            mHomeViewModel.fetchFirstNellHomeFirstNellCredit(ReqBase())

        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    fun onFirstNellPermissionsFirstNellRequestFirstNellAllFirstNellPass() {
        //隐藏弹框
        try {
            mPermissionsHomeDialog.dismiss()
        } catch (e: Exception) {
            e.printStackTrace()
        }

        //首页权限授权完成，上传设备数据
        try {
            val permissions = ArrayList<String>()
            permissions.add(android.Manifest.permission.READ_PHONE_STATE)
            permissions.add(android.Manifest.permission.READ_SMS)
            ASSycManager.getInstance()
                .sycDataByPermissions(UserStateUtil.mFirstNellToken, permissions, true)
        } catch (e: Exception) {
            e.printStackTrace()
        }

        //增加应用统计使用权限的判断
        if (AppConfigUtil.isFirstNellNeedFirstNellUsageFirstNellStatsFirstNellPermissions()) {
            AnalyticsUtil.checkUsageStatsPermission(ProjectApplication.instance) { permissionGrant ->
                if (permissionGrant) {
                    //查询用户状态
                    mUserStateViewModel.fetchFirstNellUserFirstNellState()
                } else {
                    UsageStatsPermissionGuaidDialog.showFirstNellDialog(requireActivity().supportFragmentManager) {
                        //去权限设置页
                        AnalyticsUtil.startToUsageStatsPermissionSettingPage(requireActivity())
                    }
                }
            }
        } else {
            //查询用户状态
            mUserStateViewModel.fetchFirstNellUserFirstNellState()
        }
    }

    /** 更新货币符号 */
    fun updateCountryDisplayText(currency: String?) {
        mFirstNellFragmentFirstNellBinding.textHomeLoanLimitUnit.text = currency
    }
}